package com.xzq.spring;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.xzq.register.NacosRegister;
import com.xzq.register.RedisRegister;
import com.xzq.register.Register;
import com.xzq.server.NettyServer;
import com.xzq.server.ServerChannelInitializer;
import com.xzq.server.ServerMessageHandler;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @Author xzq
 * @Description //标注了RPCService的接口在程序启动的时候进行服务注册, 标注了RpcAutowire进行动态代理
 * @Date 2021/11/23 10:21
 * @Version 1.0.0
 **/
@EnableConfigurationProperties(RpcProperties.class)
@Data
public class RpcAutoConfigration implements BeanFactoryAware {

    private RpcProperties rpcProperties;
    private BeanFactory beanFactory;
    public RpcAutoConfigration(RpcProperties rpcProperties) {
        this.rpcProperties = rpcProperties;
    }

    @Bean
    @ConditionalOnProperty(prefix = "rpc",name = "enable",havingValue = "true")
    public RpcNettyStater rpcNettyStater() {
        return new RpcNettyStater();
    }

    @Bean
    @ConditionalOnProperty(prefix = "rpc",name = "enable",havingValue = "true")
    public ServerChannelInitializer serverChannelInitializer() {
        return new ServerChannelInitializer(new ServerMessageHandler(beanFactory));
    }
    @Bean
    @ConditionalOnProperty(prefix = "rpc",name = "enable",havingValue = "true")
    public NettyServer nettyServer(ServerChannelInitializer serverChannelInitializer) {
        NettyServer nettyServer = new NettyServer(serverChannelInitializer);
        //注册虚拟机钩子函数
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            nettyServer.destory();}));
        return nettyServer;
    }

    @Bean
    public Register register() {
        RpcProperties.Register register = rpcProperties.getRegister();
        if (register.getRedis() != null) {
            return new RedisRegister(register.getRedis().getHost(), register.getRedis().getPort(), register.getRedis().getAuth());
        }else{
            try {
                return new NacosRegister(NacosFactory.createNamingService(register.getNacos().getServeraddr()));
            } catch (NacosException e) {
                e.printStackTrace();
            }
        }
        throw new RuntimeException("no register ");
    }



    @Bean
    public RpcServiceFind rpcServiceFind() {
      return   new RpcServiceFind();
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
